/**
 * 版权所有：2020，TLF工作室。
 */
package com.cqeec.gams.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.cqeec.gams.entity.Account;

/**
 * 用户权限验证拦截器。
 * 
 * @author 唐礼飞
 * @date 2020-06-11 08:51:15.255
 */
public class UserAuthorizationVerificationInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("----------------------");
		System.out.println(request.getRequestURI());
		System.out.println("----------------------");
		// 验证用户是否登录
		HttpSession session = request.getSession();
		Object obj = session.getAttribute("account");
		if (obj == null) {
			// 未登录，返回到登录页面
			response.sendRedirect(request.getContextPath() + "/login.html");
			return false;
		} else {
			// 已登录，验证用户权限
			obj = session.getAttribute("userPermission");
			if (obj == null) {
				response.sendRedirect(request.getContextPath() + "/error/401.html");
				return false;
			} else {
				List<String> userPermission = (List<String>) obj;
				String url = request.getRequestURI().replace(request.getContextPath() + "/", "");
				if (userPermission.contains(url)) {
					// 拥有此权限
					return true;
				} else {
					// 没有此权限
					response.sendRedirect(request.getContextPath() + "/error/401.html");
					return false;
				}
			}
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
